package com.simplerobot.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;


public class Util {

    /**
     * InputStream转换成byte数组<br />
     * @param stream InputStream
     * @return byte[]
     */
    public static byte[] streamToByteList(InputStream stream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int index = 0;
        try {
            while ((index = stream.read(buff, 0, 100)) > 0) {
                outputStream.write(buff, 0, index);
            }
        } catch (IOException e) {
            return new byte[0];
        }
        return outputStream.toByteArray();
    }

    /**
     * 判断是否是Windows系统
     * @return Boolean
     */
    public static Boolean isWindows() {
        String os = System.getProperty("os.name");
        return os.toLowerCase().startsWith("win");
    }

    /**
     * 验证两个列表是否有重叠项<br />
     * @param list      列表项
     * @param validList 侍检测列表项
     * @return Boolean 是否存在
     */
    public static Boolean contains(HashSet<Integer> list, int[] validList) {
        for (int item : validList) {
            if (list.contains(item)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 显示分页<br />
     * @param pageSize   每页显示的数据条数
     * @param p          当前页码
     * @param totalCount 总条数
     * @param linkUrl    链接地址，__id__代表页码
     * @param centSize   中间页码数量，值为Null时，默认值为10
     */
    public static String getPageHtml(int pageSize, int p, int totalCount, String linkUrl, Integer centSize) {
        if (centSize == null) {
            centSize = 10;
        }
        //计算页数
        if (totalCount < 1 || pageSize < 1) {
            return "";
        }
        int pageCount = totalCount / pageSize;
        if (pageCount < 1) {
            return "";
        }
        if (totalCount % pageSize > 0) {
            pageCount += 1;
        }
        if (pageCount <= 1) {
            return "";
        }
        StringBuilder pageStr = new StringBuilder();
        String firstBtn = String.format("<a href=\"%s\">«上一页</a>", linkUrl.replace("__id__", (p - 1) + ""));
        String lastBtn = String.format("<a href=\"%s\">下一页»</a>", linkUrl.replace("__id__", (p + 1) + ""));
        String firstStr = String.format("<a href=\"%s\">1</a>", linkUrl.replace("__id__", "1"));
        String lastStr = String.format("<a href=\"%s\">%d</a>", linkUrl.replace("__id__", pageCount + ""), pageCount);
        if (p <= 1) {
            firstBtn = "<span class=\"disabled\">«上一页</span>";
        }
        if (p >= pageCount) {
            lastBtn = "<span class=\"disabled\">下一页»</span>";
        }
        if (p == 1) {
            firstStr = "<span class=\"current\">1</span>";
        }
        if (p == pageCount) {
            lastStr = String.format("<span class=\"current\">%d</span>", pageCount);
        }
        int firstNum = p - (centSize / 2); //中间开始的页码
        if (p < centSize)
            firstNum = 2;
        int lastNum = p + centSize - ((centSize / 2) + 1); //中间结束的页码
        if (lastNum >= pageCount)
            lastNum = pageCount - 1;
        pageStr.append(String.format("<span>共%d记录</span>", totalCount));
        pageStr.append(firstBtn + firstStr);
        if (p >= centSize) {
            pageStr.append("<span>...</span>\n");
        }
        for (int i = firstNum; i <= lastNum; i++) {
            if (i == p) {
                pageStr.append("<span class=\"current\">" + i + "</span>");
            } else {
                pageStr.append(String.format("<a href=\"%s\">" + i + "</a>", linkUrl.replace("__id__", i + "")));
            }
        }
        if (pageCount - p > centSize - ((centSize / 2))) {
            pageStr.append("<span>...</span>");
        }
        pageStr.append(lastStr + lastBtn);
        return pageStr.toString();
    }

    /**
     * 转换文件大小成kb/mb/gb<br />
     * @param size 文件大小
     * @return String 文件大小字符串表现形式
     */
    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1fGB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0fMB" : "%.1fMB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            //%.0fKB表示不保留小数点，%.1fKB表示保留一位小数点
            return String.format(f > 100 ? "%.0fKB" : "%.1fKB", f);
        } else
            return String.format("%dB", size);
    }

    /**
     * 读取应用版本号<br />
     * @param rootPath 网站根目录
     * @return 版本号
     */
    public static String readAppVersion(String rootPath) {
        String configFilePath = null;
        if (isWindows()) {
            configFilePath = String.format("%s/target/maven-archiver/pom.properties", rootPath.substring(0, rootPath.indexOf("/target")));
        } else {
            configFilePath = String.format("%s/META-INF/maven/cn.ycmedia/admin.chengadx.com/pom.properties", rootPath);
        }
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(configFilePath));
        } catch (Exception e) {
            return "";
        }
        configFilePath = null;
        return properties.getProperty("version");
    }

    /**
     * 正则验证<br />
     */
    public static boolean regex(String value,String regexStr) {
        return Pattern.compile(regexStr).matcher(value).matches();
    }

    private static AtomicInteger counter = new AtomicInteger(0);

    /**
     * 生成唯一id<br />
     * */
    public static long createUniqueId() {
        if (counter.get() > 999999) {
            counter.set(1);
        }
        return System.currentTimeMillis() + counter.incrementAndGet();
    }

    public static void main(String[] args) {
        System.out.println(convertFileSize(10000));
    }
}